package A3D_Test 
{
	import A3D_Test.Logger;
	import A3D_Test.ModelResource;
	import alternativa.engine3d.core.Object3D;
	import alternativa.engine3d.core.Resource;
	import alternativa.engine3d.lights.AmbientLight;
	import alternativa.engine3d.lights.DirectionalLight;
	import alternativa.engine3d.lights.OmniLight;
	import alternativa.engine3d.lights.SpotLight;
	import alternativa.engine3d.objects.Mesh;
	import flash.events.Event;

	

	public class ModelInstance extends Object3D
	{
		public function ModelInstance( mdlRes:ModelResource )
		{
			if ( mdlRes.ready )
				Init( mdlRes );
			else
				mdlRes.addEventListener( Event.COMPLETE, onModelReady );
		}
		
		
		private function onModelReady( e:Event ):void
		{
			var mdlEvt:ModelResourceReadyEvent = ModelResourceReadyEvent( e );
			Init( mdlEvt.modelResource );
		}

		
		private function Init( mdlRes:ModelResource ):void
		{
			//Just clone everything for new model instance
			for each (var object:Object3D in mdlRes.parser.objects)
				if ( object is Mesh )
				{
					var srcMesh:Mesh = Mesh( object );
					var newMesh:Mesh = Mesh( srcMesh.clone() );
					newMesh.matrix = srcMesh.matrix;
					addChild( newMesh );
				}
				else if ( object is AmbientLight ) { //We have to re-create lights to circumvent some buggy A3D behaiviour
					var srcAL:AmbientLight = AmbientLight( object );
					var newAL:AmbientLight = new AmbientLight( srcAL.color );
					newAL.matrix = srcAL.matrix;
					addChild( newAL );
				}
				else if ( object is OmniLight ) {
					var srcOL:OmniLight = OmniLight( object );
					var newOL:OmniLight = new OmniLight( srcOL.color, srcOL.attenuationBegin, srcOL.attenuationEnd );
					newOL.matrix = srcOL.matrix;
					addChild( newOL );
				}
				else if ( object is DirectionalLight ) {
					var srcDL:DirectionalLight = DirectionalLight( object );
					var newDL:DirectionalLight = new DirectionalLight( srcDL.color );
					newDL.matrix = srcDL.matrix;
					addChild( newDL );
				}
				else if ( object is SpotLight ) {
					var srcSL:SpotLight = SpotLight( object );
					var newSL:SpotLight = new SpotLight( srcSL.color, srcSL.attenuationBegin, srcSL.attenuationEnd, srcSL.hotspot, srcSL.falloff );
					newSL.matrix = srcSL.matrix;
					addChild( newSL );
				}

			for each (var resource:Resource in getResources( true ) )
				resource.upload( mdlRes.context3d );
				
			Logger.Log( "Model instance '" + mdlRes.url + "' created..." );
		}
	}
}